package nio.socket.nonblocking;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Auther: luobiao
 * @Date: 2020/8/16 22:04
 * @Description:
 */
public class ThreadPoolTimeClient {
    static int connectTimeOut = 3000;
    public static void post(String host, int port, long keepalive){
        try {
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
            socketChannel.configureBlocking(false);
            long start = System.currentTimeMillis();
            while (!socketChannel.finishConnect()) {
                if (System.currentTimeMillis() - start >= connectTimeOut) {
                    throw new RuntimeException("尝试建立连接超过3秒");
                }
            }
            //如果走到这一步，说明连接建立成功
            long endTime = 0;
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            do {
                buffer.put("GET CURRENT TIME".getBytes());
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
                if (socketChannel.read(buffer) > 0) {
                    System.out.println(Thread.currentThread().getName() + " Get Current Time:" + new String(buffer.array()));
                    buffer.clear();
                }
                if (endTime == 0) { // 成功连接后才开始计算存活时间
                    endTime = System.currentTimeMillis() + keepalive;
                }
                Thread.sleep(1000);
            } while (System.currentTimeMillis() < endTime);
            socketChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
